/*
 * Copyright (C) 2006-2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;

using Gtk;
using Mono.Unix;

using DCSharp.Backend.Managers;
using DCSharp.Backend.Objects;
using DCSharp.Xml;

namespace DCSharp.Gui
{
	public class SearchResultView : ExtendedTreeView
	{
		private ActionGroup actionGroup;
		private Action downloadAction;
		private Action saveAsAction;
		private Action fileListAction;
		private Action matchQueueAction;

		#region Constructors

		public SearchResultView() : this(null)
		{
		}

		public SearchResultView(TreeModel model) : base(model)
		{
			CanActivateMultipleRows = true;

			// User interface
			ActionEntry[] entries = new ActionEntry[] {
				new ActionEntry("Download", null, Catalog.GetString("_Download"), null,
					Catalog.GetString("Save file"),
					OnDownload),
				new ActionEntry("SaveTo", Stock.SaveAs, Catalog.GetString("_Save To..."), null,
					Catalog.GetString("Save file to a different directory"),
					OnSaveAs),
				new ActionEntry("FileList", Stock.Directory, Catalog.GetString("_Browse Files"), null,
					Catalog.GetString("Browse the users files"),
					OnFileList),
				// FIXME: Need a better label and tooltip for this one.
				new ActionEntry("MatchQueue", null, Catalog.GetString("_Match Queue"), null,
					null,
					OnMatchQueue)
			};

			actionGroup = new ActionGroup("SearchResultViewActions");
			actionGroup.Add(entries);

			downloadAction = actionGroup["Download"];
			saveAsAction = actionGroup["SaveTo"];
			fileListAction = actionGroup["FileList"];
			matchQueueAction = actionGroup["MatchQueue"];

			// Columns
			TreeViewColumn column;
			CellRendererText textRenderer;
			CellRendererPixbuf pixbufRenderer;

			// Name
			column = new TreeViewColumn();
			column.Title = Catalog.GetString("Name");
			column.SortColumnId = (int)SearchResultStore.Column.Name;
			column.Expand = true;
			column.Resizable = true;
			column.Spacing = 3;
			AppendColumn(column);

			pixbufRenderer = new CellRendererPixbuf();
			column.PackStart(pixbufRenderer , false);
			column.SetCellDataFunc(pixbufRenderer, SetPixbuf);

			textRenderer = new CellRendererText();
			textRenderer.Ellipsize = Pango.EllipsizeMode.End;
			column.PackStart(textRenderer , true);
			column.AddAttribute(textRenderer, "text",
				(int)SearchResultStore.Column.Name);

			// Directory
			textRenderer = new CellRendererText();
			textRenderer.Ellipsize = Pango.EllipsizeMode.Middle;
			column = AppendColumn(Catalog.GetString("Directory"), textRenderer,
				"text", (int)SearchResultStore.Column.Directory);
			column.Expand = true;
			column.Resizable = true;
			column.SortColumnId = (int)SearchResultStore.Column.Directory;

			// Size
			textRenderer = new CellRendererText();
			column = AppendColumn(Catalog.GetString("Size"), textRenderer,
				"text", (int)SearchResultStore.Column.Size);
			column.SortColumnId = (int)SearchResultStore.Column.Bytes;

			// User
			textRenderer = new CellRendererText();
			textRenderer.Ellipsize = Pango.EllipsizeMode.End;
			column = AppendColumn(Catalog.GetString("User"), textRenderer,
				"text", (int)SearchResultStore.Column.User);
			column.Expand = true;
			column.Resizable = true;
			column.SortColumnId = (int)SearchResultStore.Column.User;

			// Slots
			textRenderer = new CellRendererText();
			column = AppendColumn(Catalog.GetString("Slots"), textRenderer,
				"text", (int)SearchResultStore.Column.Slots);
			column.SortColumnId = (int)SearchResultStore.Column.FreeSlots;

			// Connection
			textRenderer = new CellRendererText();
			column = AppendColumn(Catalog.GetString("Connection"), textRenderer, "text",
				(int)SearchResultStore.Column.Connection);
			column.SortColumnId = (int)SearchResultStore.Column.Connection;

			// TTH
			textRenderer = new CellRendererText();
			textRenderer.Ellipsize = Pango.EllipsizeMode.Middle;
			column = AppendColumn(Catalog.GetString("TTH"), textRenderer,
				"text", (int)SearchResultStore.Column.TTH);
			column.Expand = true;
			column.Resizable = true;
			column.SortColumnId = (int)SearchResultStore.Column.TTH;
		}

		#endregion

		#region Methods

		protected override void OnRowActivated(TreePath path,
			TreeViewColumn column)
		{
			TreeIter iter;
			if (Model.GetIter(out iter, path))
			{
				SearchResult result = Model.GetValue(iter,
					(int)SearchResultStore.Column.Object) as SearchResult;
				if (result != null && result.Type == ResultType.File)
				{
					Globals.Runtime.DownloadManager.Download(result);
					return;
				}
			}
			base.OnRowActivated(path, column);
		}

		protected override void OnPopulatePopup(Menu menu)
		{
			bool canDownload = false;
			foreach (SearchResult result in GetSelectedObjects(
				(int)SearchResultStore.Column.Object))
			{
				if (result.Type == ResultType.File)
				{
					canDownload = true;
				}
			}
			downloadAction.Sensitive = saveAsAction.Sensitive = canDownload;
			matchQueueAction.Sensitive = Selection.CountSelectedRows() > 0 &&
				FileDownloadsExists();

			menu.Add(downloadAction.CreateMenuItem());
			menu.Add(saveAsAction.CreateMenuItem());

			MenuItem item = new SeparatorMenuItem();
			menu.Add(item);
			item.Show();

			menu.Add(fileListAction.CreateMenuItem());
			menu.Add(matchQueueAction.CreateMenuItem());

			base.OnPopulatePopup(menu);
		}

		private void SetPixbuf(TreeViewColumn column, CellRenderer renderer,
			TreeModel model, TreeIter iter)
		{
			CellRendererPixbuf pixbufRenderer = (CellRendererPixbuf)renderer;
			SearchResult result = model.GetValue(iter,
				(int)SearchResultStore.Column.Object) as SearchResult;

			if (result != null)
			{
				if (result.Type == ResultType.Directory)
				{
					pixbufRenderer.Pixbuf = RenderIcon(Stock.Directory,
						IconSize.Menu, String.Empty);
				}
				else
				{
					pixbufRenderer.Pixbuf = Util.GetIconFromPath(result.Path);
				}
			}
		}

		private void OnDownload(object obj, EventArgs args)
		{
			TreePath[] paths = Selection.GetSelectedRows();
			foreach (TreePath path in paths)
			{
				ActivateRow(path, Columns[0]);
			}
		}

		private void OnSaveAs(object obj, EventArgs args)
		{
			object[] results = GetSelectedObjects((int)SearchResultStore.Column.Object);
			if (results.Length == 1)
			{
				SearchResult result = results[0] as SearchResult;
				if (result.Type == ResultType.Directory)
				{
					return;
				}
				string filename = SaveToDialog.GetFilename(
					StringUtil.GetFileName(result.Path), Toplevel as Window);

				if (filename != null)
				{
					Globals.Runtime.DownloadManager.Download(result,
						System.IO.Path.GetFileName(filename),
						System.IO.Path.GetDirectoryName(filename));
				}
			}
			else
			{
				string folder = SaveToDialog.GetFolder(Toplevel as Window);
				if (folder != null)
				{
					foreach (SearchResult result in results)
					{
						if (result.Type == ResultType.Directory)
						{
							continue;
						}
						Globals.Runtime.DownloadManager.Download(result,
							StringUtil.GetFileName(result.Path), folder);
					}
				}
			}
		}

		private void OnFileList(object obj, EventArgs args)
		{
			object[] results = GetSelectedObjects((int)SearchResultStore.Column.Object);
			foreach (SearchResult result in results)
			{
				Util.RequestFileList(result.User, result.Path);
			}
		}

		private void OnMatchQueue(object obj, EventArgs args)
		{
			object[] results = GetSelectedObjects((int)SearchResultStore.Column.Object);
			if (results.Length == 1)
			{
				Globals.FileFinder.CheckFileList(((SearchResult)results[0]).User);
			}
		}

		private bool FileDownloadsExists()
		{
			return null != Globals.Runtime.DownloadManager.Find<FileDownloader>(
				delegate(FileDownloader downloader)
				{
					return true;
				});
		}

		#endregion
	}
}
